//
//  LBTabBar.swift
//  JLBWeibo
//
//  Created by 蒋良彪 on 16/7/2.
//  Copyright © 2016年 Color. All rights reserved.
//

import UIKit

protocol LBTabBarDelegate: NSObjectProtocol {
    func onComposeButtonClick()
}

class LBTabBar: UITabBar {

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */
    
    weak var lbDelegate: LBTabBarDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @objc private func setupUI() {
        addSubview(composeButton)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let width = self.frame.width * 0.2
        var index: CGFloat = 0
        
        for subview in self.subviews {
            
            if subview.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                subview.frame.origin.x = index * width
                subview.frame.size.width = width
                
                index++
                
                if index == 2 {
                    index++
                }
            }
        }
        
        composeButton.center.x = self.frame.width * 0.5
        composeButton.center.y = self.frame.height * 0.5
    }
    
    @objc private func onComposeButtonClick() {
        self.lbDelegate?.onComposeButtonClick()
    }
    
    lazy var composeButton: UIButton = {
        let composeButton = UIButton()
        composeButton.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        composeButton.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        composeButton.addTarget(self, action: #selector(onComposeButtonClick), forControlEvents: UIControlEvents.TouchUpInside)
        composeButton.sizeToFit()
        return composeButton
    }()
}
